#pragma once
#include<iostream>
using namespace std;

template<class K, class V>
struct BSTreeNode
{
	BSTreeNode(K key, V val)
		: _key(key)
		, _value(val)
		, _left(nullptr)
		, _right(nullptr)
	{}

	K _key;
	V _value;
	BSTreeNode<K, V>* _left;
	BSTreeNode<K, V>* _right;
};

template<class K, class V>
class BSTree
{
	typedef BSTreeNode<K, V> Node;
public:
	BSTree()
	{}

	bool Insert(const K& key, const V& value)
	{
		if (_root == nullptr)
			_root = new Node(key, value);

		Node* cur = _root;
		Node* parent = cur;
		while (cur)
		{
			parent = cur;

			if (key < cur->_key)
				cur = cur->_left;
			else if (key > cur->_key)
				cur = cur->_right;
			else
				return false;
		}

		cur = new Node(key, value);
		if (key < parent->_key)
			parent->_left = cur;
		else
			parent->_right = cur;

		return true;
	}

	Node* Find(const K& key)
	{
		Node* cur = _root;
		while (cur)
		{
			if (key < cur->_key)
				cur = cur->_left;
			else if (key > cur->_key)
				cur = cur->_right;
			else
				return cur;
		}

		return nullptr;
	}

	bool Erase(const K& key)
	{
		Node* cur = _root;
		Node* parent = cur;
		while (cur)
		{
			if (key < cur->_key)
			{
				parent = cur;
				cur = cur->_left;
			}
			else if (key > cur->_key)
			{
				parent = cur;
				cur = cur->_right;
			}
			else
			{
				if (cur->_left == nullptr)
				{
					if (cur == _root)
					{
						_root = _root->_right;
						delete cur;
						return true;
					}

					if (cur == parent->_left)
						parent->_left = cur->_right;
					else
						parent->_right = cur->_right;
				}
				else if (cur->_right == nullptr)
				{
					if (cur == _root)
					{
						_root = _root->_left;
						delete cur;
						return true;
					}

					if (cur == parent->_left)
						parent->_left = cur->_left;
					else
						parent->_right = cur->_left;
				}
				else
				{
					Node* sublift = cur->_right;
					Node* parent = cur;
					while (sublift->_left)
					{
						parent = cur;
						sublift = sublift->_left;
					}

					swap(cur->_key, sublift->_key);
					swap(cur->_value, sublift->_value);

					if (sublift == parent->_left)
						parent->_left = sublift->_right;
					else
						parent->_right = sublift->_right;
				}

				return true;
			}
		}

		return false;
	}

	void _InOrder(Node* root)
	{
		if (!root)
			return;

		_InOrder(root->_left);
		cout << root->_key << ':' << root->_value << endl;
		_InOrder(root->_right);
	}

	void InOrder()
	{
		_InOrder(_root);
	}
private:
	Node* _root = nullptr;
};

